<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css" integrity="sha256-mUZM63G8m73Mcidfrv5E+Y61y7a12O5mW4ezU3bxqW4=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"tallgy.gitee.io","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>
<meta name="description" content="String 的方法replace​        其实这个方法就是一个替换函数，并没有什么，但是我在一个公众号（Vue中文社区）里面发现，这样的替换的结果居然不是将其替换为’, ‘，而是中间插入，所以这个我想要知道为什么。 1234let price &#x3D; &amp;#x27;123456789&amp;#x27;let priceReg &#x3D; &#x2F;(?!^)(?&#x3D;(\d&amp;#123;3&amp;#125;)+$)&#x2F;gcons">
<meta property="og:type" content="article">
<meta property="og:title" content="String方法">
<meta property="og:url" content="http://tallgy.gitee.io/2022/03/14/JavaScript/String%E6%96%B9%E6%B3%95/index.html">
<meta property="og:site_name" content="tallgy&#39;s blog">
<meta property="og:description" content="String 的方法replace​        其实这个方法就是一个替换函数，并没有什么，但是我在一个公众号（Vue中文社区）里面发现，这样的替换的结果居然不是将其替换为’, ‘，而是中间插入，所以这个我想要知道为什么。 1234let price &#x3D; &amp;#x27;123456789&amp;#x27;let priceReg &#x3D; &#x2F;(?!^)(?&#x3D;(\d&amp;#123;3&amp;#125;)+$)&#x2F;gcons">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-03-14T02:12:55.000Z">
<meta property="article:modified_time" content="2023-06-25T08:57:29.323Z">
<meta property="article:author" content="tallgy">
<meta property="article:tag" content="随笔">
<meta property="article:tag" content="JavaScript">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://tallgy.gitee.io/2022/03/14/JavaScript/String%E6%96%B9%E6%B3%95/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://tallgy.gitee.io/2022/03/14/JavaScript/String%E6%96%B9%E6%B3%95/","path":"2022/03/14/JavaScript/String方法/","title":"String方法"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>String方法 | tallgy's blog</title>
  




  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">tallgy's blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>







</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#String-%E7%9A%84%E6%96%B9%E6%B3%95"><span class="nav-number">1.</span> <span class="nav-text">String 的方法</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#replace"><span class="nav-number">1.1.</span> <span class="nav-text">replace</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%82%E6%95%B0%EF%BC%9A"><span class="nav-number">1.1.1.</span> <span class="nav-text">参数：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%96%B0%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%BD%9C%E4%B8%BA%E5%8F%82%E6%95%B0%EF%BC%9A"><span class="nav-number">1.1.1.1.</span> <span class="nav-text">新的字符串作为参数：</span></a></li></ol></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">tallgy</p>
  <div class="site-description" itemprop="description">只是一个知识的搬运工</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">107</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">32</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">74</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://tallgy.gitee.io/2022/03/14/JavaScript/String%E6%96%B9%E6%B3%95/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="tallgy">
      <meta itemprop="description" content="只是一个知识的搬运工">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="tallgy's blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          String方法
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-03-14 10:12:55" itemprop="dateCreated datePublished" datetime="2022-03-14T10:12:55+08:00">2022-03-14</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2023-06-25 16:57:29" itemprop="dateModified" datetime="2023-06-25T16:57:29+08:00">2023-06-25</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/JavaScript/" itemprop="url" rel="index"><span itemprop="name">JavaScript</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/JavaScript/%E9%9A%8F%E7%AC%94/" itemprop="url" rel="index"><span itemprop="name">随笔</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="String-的方法"><a href="#String-的方法" class="headerlink" title="String 的方法"></a>String 的方法</h1><h2 id="replace"><a href="#replace" class="headerlink" title="replace"></a>replace</h2><p>​        其实这个方法就是一个替换函数，并没有什么，但是我在一个公众号（Vue中文社区）里面发现，这样的替换的结果居然不是将其替换为’, ‘，而是中间插入，所以这个我想要知道为什么。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">let price = &#x27;123456789&#x27;</span><br><span class="line">let priceReg = /(?!^)(?=(\d&#123;3&#125;)+$)/g</span><br><span class="line"></span><br><span class="line">console.log(price.replace(priceReg, &#x27;,&#x27;)) //123,456,789</span><br></pre></td></tr></table></figure>

<p>​        先说结论：</p>
<p>​        所以简单来说，就是 ?= 这个方法可以形成这个效果。这个叫做正则表达式的先行断言和后行断言。</p>
<p>​        这里的这个 ?=p、?!p、?&lt;=p、?&lt;!p 这几个模式，我们可以在正则表达式里面进行学习，简单来说就是 ?=p，就是在p的前面为符合的条件，?!p，就是除了?=p 之外的所有。?&lt;=p，就是p的后面的条件。?&lt;!p，就是除了 ?&lt;=p 的所有。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">let priceReg = /(?=1)/g</span><br><span class="line"></span><br><span class="line">console.log(price.replace(priceReg, &#x27;,&#x27;)) //,123456789</span><br></pre></td></tr></table></figure>

<p>​        上面这个知道了。然后我们进行后续的学习 replace 方法。</p>
<h3 id="参数："><a href="#参数：" class="headerlink" title="参数："></a>参数：</h3><ul>
<li>字符串 或者 正则表达式</li>
<li>替换成新的字符串 或者 一个函数进行处理</li>
</ul>
<p>其中，对于新的字符串和函数作为参数，我们可以使用一些特殊变量名</p>
<h4 id="新的字符串作为参数："><a href="#新的字符串作为参数：" class="headerlink" title="新的字符串作为参数："></a>新的字符串作为参数：</h4><p>变量名    代表的值</p>
<ul>
<li>$$    插入一个 “$”。</li>
<li>$&amp;    插入匹配的子串。</li>
<li>$`    插入当前匹配的子串左边的内容。</li>
<li>$’    插入当前匹配的子串右边的内容。</li>
<li>$n    假如第一个参数是 RegExp对象，并且 n 是个小于100的非负整数，那么插入第 n 个括号匹配的字符串。提示：索引是从1开始。如果不存在第 n个分组，那么将会把匹配到到内容替换为字面量。比如不存在第3个分组，就会用“$3”替换匹配到的内容。</li>
<li>$<Name>     这里Name 是一个分组名称。如果在正则表达式中并不存在分组（或者没有匹配），这个变量将被处理为空字符串。只有在支持命名分组捕获的浏览器中才能使用。</Name></li>
</ul>
<p>这里我就简单说前面几个可能会常用的</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">let price = &#x27;123145617819&#x27;</span><br><span class="line">let priceReg = /1/g</span><br><span class="line">console.log(price.replace(priceReg, &#x27;$&amp;,&#x27;)) //1,231,4561,781,9</span><br></pre></td></tr></table></figure>

<p>​        上面有个案例，大概就能理解了。</p>
<ul>
<li><p>对于 $$ 不用思考，就像是 <code>\\</code> 一样，转义 <code>\</code> 的。</p>
</li>
<li><p>$&amp;，代表匹配上的字符串</p>
</li>
<li><p>$`，就是匹配字符串的左边的内容</p>
<ul>
<li>```<br>let price = ‘123145617819’<br>let priceReg = /\d{3}/gconsole.log(price.replace(priceReg, ‘$`,’)) // ,123,123145,123145617,<br>123 左侧没有，所以就只有一个 ,<br>145 左侧存在123，所以就是 123,<br>617 左侧为123145，所以就是 123145,<br>819 同上。<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">* $&#x27;，代表右边内容，意思同上。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">#### 函数作为参数</span><br><span class="line"></span><br><span class="line">变量名	代表的值</span><br><span class="line"></span><br><span class="line">* match	匹配的子串。（对应于上述的$&amp;。）</span><br><span class="line">* p1,p2, ...	假如replace()方法的第一个参数是一个RegExp 对象，则代表第n个括号匹配的字符串。（对应于上述的$1，$2等。）例如，如果是用 /(\a+)(\b+)/ 这个来匹配，p1 就是匹配的 \a+，p2 就是匹配的 \b+。</span><br><span class="line">* offset	匹配到的子字符串在原字符串中的偏移量。（比如，如果原字符串是 &#x27;abcd&#x27;，匹配到的子字符串是 &#x27;bc&#x27;，那么这个参数将会是 1）</span><br><span class="line">* string	被匹配的原字符串。</span><br><span class="line">* NamedCaptureGroup	命名捕获组匹配的对象</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>
console.log(price.replace(priceReg, () =&gt; {<br>console.log(‘1’)<br>}))</li>
</ul>
</li>
</ul>
<p>首先我们会发现，这个方法在每次匹配都会执行一次。</p>
<pre><code>
​        对于参数来说，因为参数的第二个是匹配的()，所以我们需要知道正则表达式的()的数量才能完成编写。

​        同时，返回值将替换原来的。

​        注意，此时的返回值将不能使用字符串参数里面的特殊变量了。
</code></pre>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E9%9A%8F%E7%AC%94/" rel="tag"># 随笔</a>
              <a href="/tags/JavaScript/" rel="tag"># JavaScript</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2022/03/14/%E9%9A%8F%E7%AC%94/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/" rel="prev" title="正则表达式">
                  <i class="fa fa-chevron-left"></i> 正则表达式
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2022/03/15/JavaScript/JavaScript%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2/" rel="next" title="JavaScript类型转换">
                  JavaScript类型转换 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">tallgy</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
